package com.awakensoftware.hunterserver.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.awakensoftware.hunterserver.exceptions.entityexceptions.EntityConstraintViolationException;
import com.awakensoftware.hunterserver.exceptions.entityexceptions.EntityException;
import com.awakensoftware.hunterserver.exceptions.entityexceptions.EntityValidationFailureException;
import com.awakensoftware.hunterserver.repositories.HunterRepository;
import com.awakensoftware.hunterserver.serverentities.Hunter;

@Service("hunterService")
@Scope("singleton")
@Transactional
public class HunterService extends ServerEntityServiceBase<Hunter> {

	@Autowired
	private HunterRepository hunterRepository;

	public Hunter create(String username) throws EntityException {
		Hunter hunter = new Hunter();
		hunter.setUsername(username);

		if (hunter.validate()) {
			try {
				hunterRepository.create(hunter);
			} catch (JpaSystemException e) {
				throw new EntityConstraintViolationException(e.getMostSpecificCause().getMessage());
			}
		} else {
			throw new EntityValidationFailureException();
		}

		return hunter;
	}

}
